<template>
  <div class="main ad-manage-list">
    <section>
      <div v-if="rightsButtons['setStar']" class="btn-block">
        <el-button type="success" size="small" plain @click="setStarAnchor">设置明星主播</el-button>
      </div>
      <search-form
        :listQuery="listQuery"
        :queryConfig="queryConfig"
        :labelWidth="100"
        :search="search"
      />
      <el-table
        :data="list"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        border
        highlight-current-row
      >
        <el-table-column
          align="center"
          label="用户ID"
          prop="userId"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户昵称"
          prop="nickname"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号码"
          prop="mobile"
        ></el-table-column>
        <el-table-column
        align="center"
        label="真实姓名"
        prop="realName"
      ></el-table-column>
        <el-table-column
          align="center"
          label="真实姓名"
          prop="realName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户身份"
          prop="role"
        >
          <template slot-scope="scope">
            {{scope.row.currentMemberCardType | userRole}}
          </template>
        </el-table-column>
        <!-- <el-table-column
          align="center"
          label="用户等级"
          prop="subdivisionLevel"
        >
          <template slot-scope="scope">
            {{scope.row.subdivisionLevel | userLevel}}
          </template>
        </el-table-column> -->
        <el-table-column
          align="center"
          label="粉丝数"
          prop="followNum"
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建直播数"
          width="160"
          prop="liveNum"
        ></el-table-column>
        <el-table-column
          align="center"
          label="累计成单数"
          prop="orderNum"
          width="160"
        ></el-table-column>
        <el-table-column
          align="center"
          label="主播状态"
          width="160"
        >
          <template slot-scope="scope">
            <span>
              {{scope.row.status | anchorStatus}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="直推礼包数"
          prop="giftNum"
        ></el-table-column>
        <el-table-column align="center" label="主播身份" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 1">平台主播</span>
            <span v-if="scope.row.type === 2">代理主播</span>
            <span v-if="scope.row.type === 3">热店主播</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="200"
        >
          <template slot-scope="scope">
            <el-button type="danger"   plain size="mini" @click="upStatus(scope.row,0)" v-if="scope.row.status !== 4 && rightsButtons['operate']">冻结</el-button>
            <el-button type="primary"  size="mini" plain @click="upStatus(scope.row,1)" v-else-if="rightsButtons['operate']">恢复</el-button>
            <el-button type="primary"  v-if="rightsButtons['set']"  size="mini" plain @click="showSetDialog(scope.row)" >设置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      >
      </el-pagination>
    </section>
    <el-dialog title="设置" :visible.sync="dialogSetType" width="30%">
      <el-form label-width="100px" >
        <el-form-item label="身份：">
          <el-radio-group v-model="type">
            <el-radio :label="1">平台主播</el-radio>
            <el-radio :label="2">代理主播</el-radio>
            <el-radio :label="3">热店主播</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSetType = false">取 消</el-button>
        <el-button type="primary" @click="handleSetAnchor">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="冻结" :visible.sync="dialogFreeze" width="30%" @close="handleDialogClose">
      <el-form :model="freezeForm" :rules="freezeRules" ref="freezeForm" label-width="100px">
        <el-form-item label="冻结原因" prop="approveReason">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入冻结原因"
            v-model="freezeForm.approveReason">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFreeze = false">取 消</el-button>
        <el-button type="primary" @click="handleFreeze('freezeForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="明星主播列表" :visible.sync="dialogStar" custom-class="dialog-star" width="50%">
      <div class="btn-block">
        <el-button type="primary" size="small" plain @click="addStar()">添加主播</el-button>
      </div>
      <el-table
        :data="starList"
        v-loading="starListLoading"
        header-row-class-name="table-header"
        element-loading-text="给我一点时间"
        border
        highlight-current-row
      >
        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column
          align="center"
          label="主播昵称"
          width="100"
          prop="nickname"
        ></el-table-column>
        <el-table-column
          align="center"
          label="真实姓名"
          width="100"
          prop="realName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号"
          width="120"
          prop="mobile"
        >
        </el-table-column>
        <el-table-column
          align="center"
          label="排序"
          prop="sortValue"
        >
          <template slot-scope="scope">
            <el-form
              :ref="`form${scope.row.id}`"
              :model="scope.row"
              label-position="left"
              label-width="90px"
            >
              <el-form-item label="" prop="sortValue" :show-message="false" required>
                <el-input v-model="scope.row.sortValue" placeholder="请输入排序" maxlength="8" @input="scope.row.sortValue=$event.replace(/[^\d]/g,'')"/>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="80"
        >
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="delStarAnchor(scope.$index, scope.row.starAnchorId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogStar = false">取 消</el-button>
        <el-button type="primary" @click="handleSort()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择主播" :visible.sync="dialogChooseStar" width="100%">
      <el-form
        class="search-block"
        :model="chooseStarListQuery"
        label-position="left"
        label-width="90px"
      >
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户昵称：" prop="nickname">
              <el-input v-model="chooseStarListQuery.nickname" placeholder="用户昵称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :offset="1">
            <el-form-item label="手机号：" prop="mobile">
              <el-input v-model="chooseStarListQuery.mobile" placeholder="手机号" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="btn-item">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="starSearch">搜索</el-button>
          <span class="btn-reset" @click="resetForm()">清空搜索条件</span>
        </el-form-item>
      </el-form>
      <el-table
        :data="chooseStarList"
        v-loading="chooseStarListLoading"
        element-loading-text="给我一点时间"
        @selection-change="handleSelectChange"
        @selection-all="handleSelectAll"
        border
        highlight-current-row
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户ID"
          prop="userId"
          width="75"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户昵称"
          prop="nickname"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号码"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户身份"
          prop="role"
        >
          <template slot-scope="scope">
            {{scope.row.role | userRole}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="真实姓名"
          prop="realName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="粉丝数"
          width="70"
          prop="followNum"
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建直播数"
          prop="liveNum"
        ></el-table-column>
        <el-table-column
          align="center"
          label="累计成单数"
          prop="orderNum"
        ></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleStarSizeChange"
        @current-change="handleStarCurrentChange"
        :current-page.sync="chooseStarListQuery.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="chooseStarListQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="chooseStarTotal"
        style="text-align: center"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogChooseStar = false">取 消</el-button>
        <el-button type="primary" @click="handleChooseStar()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchForm from '@/components/searchForm'
import anchorMixin from './mixin'
import {
  getAnchorList,
  setAnchorFreeze,
  setAnchorUnfreeze,
  setAnchorType
} from '@/api/bizhibo'
export default {
  name: 'bzb-anchorlist',
  mixins: [anchorMixin],
  components: {
    SearchForm
  },
  data() {
    return {
      tempStar: [],
      chooseStarTotal: 0,
      chooseStarList: [],
      chooseStarListLoading: false,
      chooseStarListQuery: {
        mobile: '',
        nickname: '',
        pageNo: 1,
        pageSize: 10
      },
      dialogChooseStar: false,
      dialogStar: false,
      starList: [],
      starListLoading: false,
      freezeForm: {
        approveReason: ''
      },
      freezeRules: {
        approveReason: [
          { required: true, message: '请输入冻结原因', trigger: 'blur' }
        ],
      },
      listTotal: 0,
      list: [],
      listLoading: false,
      listQuery: {
        idCardCode: '',
        mobile: '',
        nickname: '',
        realName: '',
        status: '',
        userIdentity: [],
        liveUserId: '',
        pageNo: 1,
        pageSize: 10,
        type:''
      },
      queryConfig: [
        {
          prop: 'liveUserId',
          type: 'input',
          label: '用户ID',
          maxlength: '100'
        },
        {
          prop: 'nickname',
          type: 'input',
          label: '用户昵称'
        },
        {
          prop: 'mobile',
          type: 'input',
          label: '手机号码'
        },
        // {
          // prop: 'userIdentity',
          // type: 'cascader',
          // label: '用户身份',
          // data: [
          //   {
          //     value: '0',
          //     label: '普通会员',
          //   },
          //   {
          //     value: '1',
          //     label: 'VIP会员',
          //   },
          //   {
          //     value: '2',
          //     label: '钻石会员',
          //   },
          //   {
          //     value: '3',
          //     label: '董事会员',
          //   },
          // ],
          // data: [
          //   {
          //     value: '0',
          //     label: '普通用户',
          //     children: [
          //       {
          //         value: 1,
          //         label: 'LV1'
          //       }
          //     ]
          //   },
          //   {
          //     value: 2,
          //     label: '大区',
          //     children: [
          //       {
          //         value: 1,
          //         label: 'LV1'
          //       },
          //       {
          //         value: 2,
          //         label: 'LV2'
          //       },
          //       {
          //         value: 3,
          //         label: 'LV3'
          //       },
          //       {
          //         value: 4,
          //         label: 'LV4'
          //       },
          //       {
          //         value: 5,
          //         label: 'LV5'
          //       },
          //       {
          //         value: 6,
          //         label: 'LV6'
          //       },
          //       {
          //         value: 7,
          //         label: 'LV7'
          //       },
          //       {
          //         value: 8,
          //         label: 'LV8'
          //       },
          //       {
          //         value: 9,
          //         label: 'LV9'
          //       }
          //     ]
          //   },
          //   {
          //     value: 3,
          //     label: '董事',
          //     children: [
          //       {
          //         value: 1,
          //         label: 'LV1'
          //       },
          //       {
          //         value: 2,
          //         label: 'LV2'
          //       },
          //       {
          //         value: 3,
          //         label: 'LV3'
          //       },
          //       {
          //         value: 4,
          //         label: 'LV4'
          //       },
          //       {
          //         value: 5,
          //         label: 'LV5'
          //       },
          //       {
          //         value: 6,
          //         label: 'LV6'
          //       },
          //       {
          //         value: 7,
          //         label: 'LV7'
          //       },
          //       {
          //         value: 8,
          //         label: 'LV8'
          //       }
          //     ]
          //   }
          // ]
        // },
        {
          prop: 'status',
          type: 'select',
          label: '主播状态',
          data: [
            {
              label: '正常',
              value: '2'
            },
            {
              label: '冻结',
              value: '4'
            }
          ]
        },
        {
          prop: 'type',
          type: 'select',
          label: '主播身份',
          data: [
            {
              label: '平台主播',
              value: '1'
            },
            {
              label: '代理主播',
              value: '2'
            },
            {
              label: '热店主播',
              value: '3'
            }
          ]
        }
      ],
      dialogSetType: false,
      dialogFreeze: false,
      anchorInfo: {},
      type: '',
      freezeId: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetForm (name) {
      this.chooseStarListQuery.nickname = ''
      this.chooseStarListQuery.mobile = ''
      this.getChooseStarList()
    },
    // 全选主播
    handleSelectAll (selection) {
      this.tempStar = selection
    },
    // 选中主播
    handleSelectChange (selection) {
      this.tempStar = selection
    },
    // 添加明星主播
    addStar () {
      if (this.starList.length > 20) {
        this.$message.warning('最多只能添加20个主播')
        return
      }
      this.dialogChooseStar = true
      this.getChooseStarList()
    },
    // 明星主播列表排序
    async handleSort () {
      if (this.starList.length > 20) {
        this.$message.warning('最多只能添加20个主播')
        return
      }
      let arrMap = this.starList.map((item) => {
        if (this.$refs[`form${item.id}`]) {
          return this.$refs[`form${item.id}`].validate().catch(err=>{ console.log(err) })
        }
      })
      let resultArr = await Promise.all(arrMap)
      if (resultArr.indexOf(undefined) === -1) {
        this.request({
          url: `/live-bzb-manage/anchor/star/save`,
          method: 'post',
          data: this.starList
        }).then((res) => {
          if (res.status === 200) {
            this.$message.success('保持成功')
            this.getStarList()
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.$message.error('排序必填')
      }
    },
    // 选择明星主播
    handleChooseStar () {
      for (let i = 0; i < this.tempStar.length; i++) {
        for (let j = 0; j < this.starList.length; j++ ) {
          if (this.tempStar[i].id === this.starList[j].id) {
            this.tempStar.splice(i, 1);
          }
        }
      }
      this.starList = this.starList.concat(this.tempStar)
      this.dialogChooseStar = false
    },
    // 设置明星主播
    setStarAnchor () {
      this.dialogStar = true
      this.getStarList()
    },
    // 删除明星主播
    delStarAnchor (index, id) {
      this.$confirm('确认删除该明星主播？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (id) {
          this.request({
            url: `/live-bzb-manage/anchor/star/delete/${id}`,
            method: 'post',
            data: {
              id: id
            }
          }).then((res) => {
            if (res.status === 200) {
              this.$message(res.message)
              this.getStarList()
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.starList.splice(index, 1);
        }
      })
    },
    // 获取明星主播列表
    getStarList() {
      this.starListLoading = true
      this.request({
        url: '/live-bzb-manage/anchor/star/query',
        method: 'get'
      }).then(({data, totalCount}) => {
        this.starList = data
        this.starListLoading = false
      }).catch(err => {
        console.log(err)
        this.starList = []
        this.starListLoading = false
      })
    },
    // 处理冻结弹框关闭
    handleDialogClose () {
      this.freezeForm.approveReason = ''
      this.$refs['freezeForm'].clearValidate()
    },
    async getList() {
      try {
        const params = {
          ...this.listQuery,
          role: this.listQuery.userIdentity[0],
          subdivisionLevel: this.listQuery.userIdentity[1]
        }
        delete params.userIdentity
        this.listLoading = true;
        const { data } = await getAnchorList(params)
        this.listLoading = false;
        this.list = data.records
        this.listTotal = data.total
      } catch (error) {
        console.log(error)
        this.listLoading = false;
      }
    },
    async getChooseStarList() {
      try {
        const params = {
          ...this.chooseStarListQuery,
          status: 2
        }
        this.chooseStarListLoading = true;
        const { data } = await getAnchorList(params)
        this.chooseStarListLoading = false;
        this.chooseStarList = data.records
        this.chooseStarTotal = data.total
      } catch (error) {
        console.log(error)
        this.chooseStarListLoading = false;
      }
    },
    upStatus(val, status) {
      if (status === 0) {
        this.dialogFreeze = true
        this.freezeId = val.userId
      } else {
        this.$confirm('是否确认'+(status ===0 ? '冻结':'恢复'), '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then( async () => {
          try {
            let data = null
            data = await setAnchorUnfreeze(val.userId)
            if (data.msg === 'SUCCESS') {
              this.$message.success('操作成功')
            }
            this.getList()
          } catch (error) {
            console.log(error)
            // this.$message.error('操作失败')
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 选择主播列表搜索
    starSearch() {
      this.chooseStarListQuery.pageNo = 1
      this.getChooseStarList()
    },
    // 选择主播列表切换分页
    handleStarCurrentChange(page) {
      this.chooseStarListQuery.pageNo = page
      this.getChooseStarList()
    },
    // 选择主播列表切换分页数
    handleStarSizeChange(pageSize) {
      this.chooseStarListQuery.pageSize = pageSize
      this.getChooseStarList()
    },
    // 搜索
    search() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageNo = page
      this.getList()
    },
    // 切换分页数
    handleSizeChange(pageSize) {
      this.listQuery.pageSize = pageSize
      this.getList()
    },
    // 设置主播身份弹窗
    showSetDialog(info){
      this.dialogSetType = true
      this.anchorInfo = info
      this.type = info.type
    },
    handleSetAnchor(){
      setAnchorType({
        type: this.type,
        uid: this.anchorInfo.userId
      }).then(res => {
        if (res.code === 200) {
          const index = this.list.findIndex(i => i.userId === this.anchorInfo.userId)
          this.list[index].type = this.type
          this.anchorInfo = {}
          this.dialogSetType = false
        }
      }).catch(err => {
        console.log(err)
        this.$message.error('操作失败')
      })
    },
    // 冻结主播确定操作
    handleFreeze (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          setAnchorFreeze({
            liveReasonDto: this.freezeForm.approveReason,
            userId : this.freezeId
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('冻结成功')
              this.freezeForm.approveReason = ''
              this.dialogFreeze = false
              this.getList()
            }
          }).catch(err => {
            console.log(err)
            this.$message.error('操作失败')
          })
        } else {
          this.dialogFreeze = true
          this.$message.error('冻结原因必填')
        }
      })
    }
  }
}
</script>

<style lang="scss" scope>
  .dialog-star {
    .el-form-item {
      margin-bottom: 0;
    }
  }
</style>
